import store from '@/js/store/state.js';
import base from '@/js/main/attribute/base.js';
import util from '@/js/util/util.js';
import status from '@/js/main/status.js';
import history from '@/js/main/history.js';
import line from '@/js/main/line.js';
import register from '@/js/main/register.js';
import PATH from '@/js/util/path.js';
import request from '@/js/util/url.js';
import user from '@/js/util/user.js';
import JQuery from 'jquery';
import bus from '@/js/event/bus.js';
import scene from '@/js/main/scene.js';
import {versionList} from '@/js/util/version.js';
import group from '@/js/element/group.js';

let shortcut = {
    message: null,
    confirm: null,
    saveTime: 0,
    autoSaveTimer: null,
    currentElementList: [],
    initialize: function() {
        this.destroy();
        document.addEventListener('keydown', this.keyDown);
        document.addEventListener('keyup', this.keyUp);
    },
    destroy: function() {
        document.removeEventListener('keydown', this.keyDown);
        document.removeEventListener('keyup', this.keyUp);
        this.message = null;
        this.confirm = null;
        this.saveTime = 0;
        this.autoSaveTimer = null;
        this.currentElementList = [];
    },
    boxMove: function(left, top) {
        let currentElementList = store.getCurrentElementList();
        let canvas = store.getCanvas();
        for (let i = 0; i < currentElementList.length; i ++) {
            if (left) {
                base.setLeftPixel(currentElementList[i], canvas.width, currentElementList[i].style.left.pixel + left);
            }
            if (top) {
                base.setTopPixel(currentElementList[i], canvas.height, currentElementList[i].style.top.pixel + top);
            }
        }
    },
    copyElementList: function(deleteElement = false) {
        let currentElementList = store.getCurrentElementList();
        if (currentElementList.length > 0) {
            this.cleanCurrentElementList();
            for (let i = 0; i < currentElementList.length; i ++) {
                this.currentElementList.splice(i, 0, currentElementList[i]);
            }
            this.deleteElement = deleteElement;
            if (this.message) {
                if (this.currentElementList.length > 0) {
                    this.message('成功复制' + this.currentElementList.length + '个组件', 'success');
                }
            }
        }
    },
    pasteElementList: function() {
        if (this.currentElementList.length > 0) {
            let canvas = store.getCanvas();
            let elementList = null;
            if (this.deleteElement) {
                elementList = this.currentElementList;
                store.batchRemoveElement(elementList);
            } else {
                elementList = util.clone(this.currentElementList);
            }
            for (let i = 0; i < elementList.length; i ++) {
                if (!this.deleteElement) {
                    elementList[i].id = util.getID();
                }
                elementList[i].attribute.page = store.getPageIndex();
                base.setLeftPixel(elementList[i], canvas.width, elementList[i].style.left.pixel + 50);
                base.setTopPixel(elementList[i], canvas.height, elementList[i].style.top.pixel + 50);
                store.addElement(elementList[i]);
            }
            store.setCurrentElementList(elementList);
            if (this.deleteElement) {
                history.addHistory(store.clone(), 27);
            } else {
                history.addHistory(store.clone(), 26);
            }
            line.setElementList(elementList);
            if (this.message) {
                if (this.deleteElement) {
                    this.message('成功剪切' + elementList.length + '个组件', 'success');
                } else {
                    this.message('成功粘贴' + elementList.length + '个组件', 'success');
                }
            }
            this.cleanCurrentElementList();
        }
    },
    composeElementList: function() {
        let currentElementList = store.getCurrentElementList();
        let element = util.clone(group);
        element.id = util.getID();
        let children = util.clone(currentElementList);
        element.attribute.children = children;
        element.attribute.page = store.getPageIndex();
        this.resetBoxGroup(element, currentElementList);
        this.removeElement();
        store.addElement(element);
        store.setCurrentElementList([element]);
        line.setElement(element);
    },
    resetBoxGroup: function(element, currentElementList, current, flag = false) {
        let canvas = store.getCanvas();
        let areaData = util.getElementBoxList(currentElementList);
        let style = {
            top: 0,
            left: 0,
            right: 0,
            bottom: 0
        };
        for (let index = 0; index < areaData.length - 1; index++) {
            const item1 = areaData[index];
            const item2 = areaData[index + 1];
            if (index === 0) {
                style.left = Math.min(item1.left, item2.left);
                style.top = Math.min(item1.top, item2.top);
                style.right = Math.max(item1.right, item2.right);
                style.bottom = Math.max(item1.bottom, item2.bottom);
            } else {
                style.left = Math.min(item1.left, item2.left, style.left);
                style.top = Math.min(item1.top, item2.top, style.top);
                style.right = Math.max(item1.right, item2.right, style.right);
                style.bottom = Math.max(item1.bottom, item2.bottom, style.bottom);
            }
        }
        style.width = util.toInteger(style.right - style.left);
        style.height = util.toInteger(style.bottom - style.top);
        base.setTopPixel(element, canvas.height, util.toInteger(style.top));
        base.setLeftPixel(element, canvas.width, util.toInteger(style.left));
        base.setHeightPixel(element, canvas.height, style.height);
        base.setWidthPixel(element, canvas.width, style.width);

        for (let i = 0; i < element.attribute.children.length; i++) {
            const item = element.attribute.children[i];
            item.attribute.pOption = {};
            item.attribute.pOption.pid = element.id;
            item.attribute.pOption.groupStyle = {};
            const itemstyle = util.clone(item.style);
            item.attribute.pOption.groupStyle = itemstyle;
            item.attribute.pOption.groupStyle.top.pixel = (itemstyle.top.pixel - style.top) / style.height;
            item.attribute.pOption.groupStyle.left.pixel = (itemstyle.left.pixel - style.left) / style.width;
            item.attribute.pOption.groupStyle.height.pixel = itemstyle.height.pixel / style.height;
            item.attribute.pOption.groupStyle.width.pixel = itemstyle.width.pixel / style.width;
            // base.setTopPixel(item.attribute.pOption.groupStyle, style.height, (itemstyle.top.pixel - style.top) / style.height);
            // base.setLeftPixel(item.attribute.pOption.groupStyle, style.width, (itemstyle.left.pixel - style.left) / style.width);
            // base.setHeightPixel(item.attribute.pOption.groupStyle, style.height, itemstyle.height.pixel / style.height);
            // base.setWidthPixel(item.attribute.pOption.groupStyle, style.width, itemstyle.width.pixel / style.width);
        }
        if (flag) {
            base.setTopPixel(current, canvas.height, current.style.top.pixel, true);
            base.setLeftPixel(current, canvas.width, current.style.left.pixel, true);
            base.setHeightPixel(current, canvas.height, current.style.height.pixel, true);
            base.setWidthPixel(current, canvas.width, current.style.width.pixel, true);
        }
    },
    changeBoxGroup: function(element) {
        if (element.attribute.hasOwnProperty("pOption") && element.attribute.pOption.hasOwnProperty("pid")) {
            let parent = store.getElementById(element.attribute.pOption.pid);
            this.resetBoxGroup(parent, parent.attribute.children, element, true);
        }
    },
    deComposeElement: function() {
        let currentElementList = store.getCurrentElementList();
        const parentStyle = currentElementList[0].style;
        const children = currentElementList[0].attribute.children;
        const components = [];
        for (let index = 0; index < children.length; index++) {
            const element = children[index];
            const parentCenter = {
                x: (parentStyle.width.pixel / 2) + parentStyle.left.pixel,
                y: (parentStyle.height.pixel / 2) + parentStyle.top.pixel
            };
            const componentRect = {
                top: element.attribute.pOption.groupStyle.top.pixel * parentStyle.height.pixel + parentStyle.top.pixel,
                left: element.attribute.pOption.groupStyle.left.pixel * parentStyle.width.pixel + parentStyle.left.pixel,
                bottom: element.attribute.pOption.groupStyle.top.pixel * parentStyle.height.pixel + element.attribute.pOption.groupStyle.height.pixel * parentStyle.height.pixel + parentStyle.top.pixel,
                right: element.attribute.pOption.groupStyle.left.pixel * parentStyle.width.pixel + element.attribute.pOption.groupStyle.width.pixel * parentStyle.width.pixel + parentStyle.left.pixel
            };
            const componentCenter = {
                x: (componentRect.left + componentRect.right) / 2,
                y: (componentRect.top + componentRect.bottom) / 2
            };
            const newComponentCenter = util.rotateCoordinate(componentCenter, parentCenter, parentStyle.rotate);
            element.style.rotate = Number(util.translateWholeTurn(element.style.rotate + parentStyle.rotate).toFixed(2));
            element.style.width.pixel = util.toInteger(element.attribute.pOption.groupStyle.width.pixel * parentStyle.width.pixel);
            element.style.height.pixel = util.toInteger(element.attribute.pOption.groupStyle.height.pixel * parentStyle.height.pixel);
            element.style.left.pixel = util.toInteger(newComponentCenter.x - (element.style.width.pixel) / 2);
            element.style.top.pixel = util.toInteger(newComponentCenter.y - (element.style.height.pixel) / 2);
            delete element.attribute.pOption.groupStyle;
            delete element.attribute.pOption.pid;
            components.push(element);
        }
        this.removeElement();
        for (let index = 0; index < components.length; index++) {
            const element = components[index];
            store.addElement(element);
        }
    },
    getCurrentElementList: function() {
        return this.currentElementList;
    },
    cleanCurrentElementList: function() {
        for (let i = this.currentElementList.length - 1; i >= 0; i --) {
            this.currentElementList.splice(i, 1);
        }
        return this;
    },
    setElementLock: function(locked) {
        let currentElementList = store.getCurrentElementList();
        if (currentElementList.length > 0) {
            let success = false;
            for (let i = 0; i < currentElementList.length; i ++) {
                if (locked != currentElementList[i].attribute.locked) {
                    success = true;
                }
                currentElementList[i].attribute.locked = locked;
            }
            success && history.addHistory(store.clone(), locked ? 28 : 29);
        }
        return this;
    },
    removeElement: function() {
        let currentElementList = store.getCurrentElementList();
        if (currentElementList.length > 0) {
            line.removeElementList(currentElementList);
            store.batchRemoveElement(currentElementList);
            history.addHistory(store.clone(), 6);
            store.setCurrentElementList([]);
        }
    },
    clearCanvas: function() {
        let _this = this;
        if (this.confirm) {
            this.confirm('是否要清除画布？', '', function() {
                line.initialize();
                store.setElementList([]);
                history.addHistory(store.clone(), 14);
            }, function() {
                _this.message('取消清除画布！', 'info');
            });
        }
    },
    updateAutoSave: function(time) {
        this.saveTime = time;
        if (time) {
            this.message('启用自动保存', 'success');
        } else {
            this.message('禁用自动保存', 'success');
        }
        this.saveProject();
    },
    clearAutoSaveTimer: function() {
        this.autoSaveTimer && window.clearTimeout(this.autoSaveTimer);
        this.autoSaveTimer = null;
    }
};
shortcut.keyDown = function(e) {
    if (e.ctrlKey && !e.altKey && !e.shiftKey && e.keyCode == 83) {
        e.stopPropagation();
        e.preventDefault();
        if (status.isShortcut()) {
            this.saveProject();
        }
    } else if (status.isShortcut()) {
        if ((e.target == null || (e.target.tagName != 'INPUT' && e.target.tagName != 'SELECT' && e.target.tagName != 'TEXTAREA'))
        && (store.getCurrentElementList().length > 0 || this.currentElementList.length > 0 || e.keyCode == 32 || (e.keyCode == 69)) && (status.isEditTable() === false)) {
            if (e.ctrlKey && !e.altKey && !e.shiftKey) {
                if (e.keyCode == 67 || e.keyCode == 88 || e.keyCode == 86 || e.keyCode == 89 || e.keyCode == 90 || e.keyCode == 76 || e.keyCode == 85 || e.keyCode == 69) {
                    e.stopPropagation();
                    e.preventDefault();
                }
            } else if (!e.ctrlKey && !e.altKey && !e.shiftKey) {
                if (e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40 || e.keyCode == 32 || e.keyCode == 46) {
                    e.stopPropagation();
                    e.preventDefault();
                }
            }
            if (e.ctrlKey && !e.altKey && !e.shiftKey) {
                if (e.keyCode == 67) {
                    this.copyElementList(false);
                } else if (e.keyCode == 88) {
                    this.copyElementList(true);
                } else if (e.keyCode == 86) {
                    this.pasteElementList();
                } else if (e.keyCode == 89) {
                    let state = history.moveToNext();
                    if (state) {
                        store.set(state);
                        register.redrawAll();
                        line.initialize();
                        line.setElementList(store.getElementList());
                    }
                } else if (e.keyCode == 90) {
                    let state = history.moveToPrevious();
                    if (state) {
                        store.set(state);
                        register.redrawAll();
                        line.initialize();
                        line.setElementList(store.getElementList());
                    }
                } else if (e.keyCode == 76) {
                    this.setElementLock(true);
                } else if (e.keyCode == 85) {
                    this.setElementLock(false);
                } else if (e.keyCode == 69) {
                    store.getElementList().length > 0 && this.clearCanvas();
                }
            } else if (!e.ctrlKey && !e.altKey && !e.shiftKey) {
                if (e.keyCode == 37) {
                    this.boxMove(-1, 0);
                } else if (e.keyCode == 38) {
                    this.boxMove(0, -1);
                } else if (e.keyCode == 39) {
                    this.boxMove(1, 0);
                } else if (e.keyCode == 40) {
                    this.boxMove(0, 1);
                } else if (e.keyCode == 32) {
                    status.setCanvasMove(true);
                } else if (e.keyCode == 46) {
                    this.removeElement();
                }
            }
        } else {
        }
    }
}.bind(shortcut);

shortcut.keyUp = function(e) {
    if (status.isShortcut()) {
        if ((e.target == null || (e.target.tagName != 'INPUT' && e.target.tagName != 'SELECT' && e.target.tagName != 'TEXTAREA'))
            && (store.getCurrentElementList().length > 0 || this.currentElementList || e.keyCode == 32) && status.isEditTable() === false) {
            if (e.ctrlKey && !e.altKey && !e.shiftKey) {
                if (e.keyCode == 67 || e.keyCode == 88 || e.keyCode == 86 || e.keyCode == 89 || e.keyCode == 90 || e.keyCode == 76 || e.keyCode == 85) {
                    e.stopPropagation();
                    e.preventDefault();
                }
            } else if (!e.ctrlKey && !e.altKey && !e.shiftKey) {
                if (e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40 || e.keyCode == 32 || e.keyCode == 46) { 
                    e.stopPropagation();
                    e.preventDefault();
                }
            }
            if (e.ctrlKey && !e.altKey && !e.shiftKey) {
            } else if (!e.ctrlKey && !e.altKey && !e.shiftKey) {
                if (e.keyCode == 37) {
                    history.addHistory(store.clone(), 3);
                    line.setElementList(store.getCurrentElementList());
                } else if (e.keyCode == 38) {
                    history.addHistory(store.clone(), 3);
                    line.setElementList(store.getCurrentElementList());
                } else if (e.keyCode == 39) {
                    history.addHistory(store.clone(), 3);
                    line.setElementList(store.getCurrentElementList());
                } else if (e.keyCode == 40) {
                    history.addHistory(store.clone(), 3);
                    line.setElementList(store.getCurrentElementList());
                } else if (e.keyCode == 32) {
                    status.setCanvasMove(false);
                }
            }
        } else {
        }
    }
}.bind(shortcut);

shortcut.saveProject = function(e) {
    let canvas = store.getCanvas();
    try {
        if (util.isBlank(canvas.name)) {
            this.message('请输入大屏名称', 'warning');
        } else {
            let id = scene.getID();
            let url = !util.isBlank(id) ? request.updateTemplate : request.insertTemplate;
            let projectAttr = store.clone();
            // projectAttr.history = history.getHistoryList();
            let blob = new Blob([JSON.stringify(projectAttr)]);
            let elementFile = new File([blob], 'attribute');
            let file = new FormData();
            file.set('token', user.getToken());
            file.set('name', canvas.name);
            file.set('attribute', elementFile);
            file.set('version', versionList[versionList.length - 1].version);
            if (!util.isBlank(id)) {
                file.set('id', id);
            }
            if (canvas.icon && canvas.icon.indexOf('data:image') == 0) {
                file.set('preview', util.base64ToFile(canvas.icon), '');
            }
            let _this = this;
            JQuery.ajax({
                url: url,
                async: true,
                contentType: false,
                processData: false,
                type: 'POST',
                data: file,
                success: function(result) {
                    if (result && result.state && result.state.code && result.state.code === 10000) {
                        if (result.body.message !== '1') {
                            scene.setID(result.body.message);
                            // bus.getProjectLink();
                        }
                        if (_this.message) {
                            _this.message('保存成功', 'success');
                        }
                    } else {
                        if (_this.message) {
                            _this.message(result && result.body && result.body.message ? result.body.message : '保存失败', 'error');
                        }
                    }
                }
            });
        }
    } catch (e) {
    }
    this.clearAutoSaveTimer();
    if (this.saveTime) {
        this.autoSaveTimer = window.setTimeout(this.saveProject, this.saveTime);
    }
}.bind(shortcut);
export default shortcut;